<?php
/**
 * Created by PhpStorm.
 * User: maskerj
 * Date: 2017/9/4
 * Time: 下午5:41
 */

class Login_model extends CI_Model{
    public function __construct()
    {
        parent::__construct();
        $this->load->database();
    }

    /**
     * @param $username
     * @param $password
     * @return array
     * 用户登录检验
     */
    public function checkLogin($username,$password){
        //检查用户名是否存在
        $hasUser = $this->db->select('id,password,password_salt')->from('users')
            ->where('username',$username)
            ->get()->row_array();
        if(!empty($hasUser)){
            //检查用户密码
            if($hasUser['password'] == sha1($hasUser['password_salt'].$password)){
                //密码正确检查账号是否被禁用
                $disable = $this->db->select('id')->from('users_permissions')
                    ->where('userid',$hasUser['id'])
                    ->where('permid',1)
                    ->get()->row_array();
                if(!empty($disable)){
                    return [
                        'code' => 0,
                        'msg'  => '该用户已被禁用!'
                    ];
                }else{
                    //更新用户登录信息
                    $this->db->where('id',$hasUser['id']);
                    $this->db->update('users',[
                        'ipaddress' =>  $_SERVER["REMOTE_ADDR"],
                        'time'      =>  time()
                    ]);
                    //存入session
                    $this->session->set_userdata("uid",$hasUser["id"]);

                    return [
                        'code' => 1,
                        'msg'  => '登录成功!'
                    ];
                }
            }else{
                return [
                    'code' => 0,
                    'msg'  => '用户名密码错误!'
                ];
            }
        }else{
            return [
                'code' => 0,
                'msg'  => '用户名不存在!'
            ];
        }
    }
}